package middleware

import (
	"github.com/gin-gonic/gin"
	"user-web/src/api"
	"user-web/src/request"
	"user-web/src/util"
)

var anonymous = []string{
	"/v1/user/login",
}

func AuthRequired() gin.HandlerFunc {
	return func(c *gin.Context) {
		path := c.Request.URL.Path
		if util.In(path, anonymous) {
			c.Next()
			return
		}

		bearerToken := c.GetHeader("Authorization")
		if bearerToken == "" {
			api.JSON(c, api.JsonError(api.JwtValidationErr))
			return
		}
		//校验token 是否是当前用户的
		var info request.InfoRequest
		if err := c.ShouldBindJSON(&info); err != nil {
			api.JSON(c, api.JsonError(api.JwtValidationErr))
			return
		}
		jwtToken := util.ValidateJwt(bearerToken, info.Username)
		if !jwtToken {
			api.JSON(c, api.JsonError(api.JwtValidationErr))
			return
		}
		c.Next()
	}
}
